--[[
	是一个service，专门发送邮件，一个人最多保存20条
	并且写入是否读取邮件表 rs_readmail, 不写入mysql，只在redis里面存储
]]

local filename = "mailbox.lua"

local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

local filelog = require "filelog"
local timetool = require "timetool"
local tabletool = require "tabletool"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local routerbase = require "routerbase"

local Mail = routerbase:new()

local limit = 50

-- 检查已经有多少条邮件，再按时间逆序删除多余的
local function limit_mail(rid)
	local status, result = skynet.pcall(cluster.call, "datanode", ".router", "select_rk", rid, "rm_mail")
	--filelog.print(result[1])

	if not status or not result then return false end
	if result[1] and result[1] < limit then return true end
	
	--删除过期邮件
    if result and result[2] then
        local curtime = timetool.get_time()
        local outtime = curtime - 3600 * 120 --过期时间5天
	    for k,v in pairs(result[2]) do
		    if v.create_time < outtime  then
                local attach_json = json.decode(v.attach_json)
                if not attach_json or not attach_json.diamond then
                    cluster.send("datanode", ".router", "delete_rk", rid, "rm_mail", v.keyid)
                end
           end
	    end
    end
end

local function write_mail(rid, fields)
    fields = fields or {}
    if type(fields.attach_json) == "table" then
        fields.attach_json = json.encode(fields.attach_json)
    end
    if fields.attach_json and type(fields.attach_json) ~= "string" then
        filelog.sys_error("error mail attach format!", rid, fields)
        return
    end

	local keyid = skynet.call(".nodeuuid", "lua", "getuuid")
	local status, result = skynet.pcall(cluster.call, "datanode", ".router", "insert_rk", rid, "rm_mail", keyid, fields)
	-- 正常情况下，肯定数据库里面已经有这个记录了
	-- result = cluster.call("datanode", ".router", "select_rk", rid, "rs_readmail")
	-- 更新最新发送时间
	local now = timetool.get_time()
	status, result = skynet.pcall(cluster.call, "datanode", ".router", "update_rk", rid, "rs_readmail", 0, {last_sendtime=now})
	local agent = skynet.call(".mainnode", "lua", "cmd", "get_agent_by_rid", rid)
	if agent then
		skynet.send(agent, "lua", "cmd", "notify_client", "newmailN", {sendtime=now})
	end

    --保存附件邮件日志 操作名 操作id rid keyid 附件json编码
    local logstr = string.format("%s,%d,%d,%d,%s","new_mail", 1, rid, keyid, fields.attach_json)
    skynet.send(".maillog", "lua", "write", logstr)
	
	return keyid
end

-- 在router里面的 newmail 调用
function Mail.CMD.newmail(rid, fields)
	limit_mail(rid)	
	return write_mail(rid, fields)
end


skynet.start(function()
	Mail:start()
end)
